package www.my.imageframecompare.myGlide;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.FutureTarget;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutionException;

import www.my.imageframecompare.R;

/**
 * Created by 张英杰 on 2016/8/11.
 */
public class GlideShow extends AppCompatActivity {
    private static final String TAG = "GlideShow====";
    ImageView iv_local;
    ImageView iv_local_two;
    String imgLocalPath ;
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bitmap bmp = BitmapFactory.decodeFile(imgLocalPath);
            Log.e("Handlerpath===",(bmp!=null)?(bmp.getHeight()+"--"+bmp.getRowBytes()):"null");
            Glide.with(GlideShow.this)
                    .load(imgLocalPath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(iv_local_two);
        }
    };

    public static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
            Log.i(TAG, "close===");
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imageloasershow);
        File folderFile = getCacheDir().getAbsoluteFile();
//        String folder = Environment.getExternalStorageDirectory()+File.separator+"abc";
//        File folderFile = new File(folder);
        if (!folderFile.exists()){
            folderFile.mkdirs();
        }
        imgLocalPath = folderFile.toString()+File.separator+ "AAbc.jpg";
//        final String img = getIntent().getStringExtra("img");
//        final String img = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3122590414,1026621252&fm=11&gp=0.jpg";
//        final String img = "http://img2.imgtn.bdimg.com/it/u=1485880718,1257114420&fm=11&gp=0.jpg";
        final String img="http://img4.imgtn.bdimg.com/it/u=202447557,2967022603&fm=27&gp=0.jpg";
        ImageView iv = (ImageView) findViewById(R.id.iv);
        iv_local = (ImageView) findViewById(R.id.iv_local);
        iv_local_two = (ImageView) findViewById(R.id.iv_local_two);
//        final String pathSD = "/storage/emulated/0/zhongzi/2016-10-17-15-15-19.jpg";
//        if (pathSD.contains("/storage/")&&!pathSD.contains("file:///")){
////            File file = new File(pathSD);
//            pathSD="file://"+pathSD;
//            Log.i("pathSd12====",pathSD);
//        }
        //glide
        Glide.with(GlideShow.this)
                .load(img)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .thumbnail((float) 0.2)
                .placeholder(R.drawable.image_loading)
                .error(R.drawable.image_error)
                .into(iv);
        findViewById(R.id.btn_SaveImg).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new GetImageCacheAsyncTask(GlideShow.this,iv_local).execute(img);
                        File folderFile = getCacheDir().getAbsoluteFile();
                        Log.i(TAG, "onClick: "+!folderFile.exists());
                        if (!folderFile.exists()){
                            folderFile.mkdirs();
                        }
                        saveImg(img);

                    }
                }
        );
    }

    private void saveImg(final String imgUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String imgPathFromCache = getImgPathFromCache(imgUrl);
                Log.i(TAG, "onClick: " + imgPathFromCache);
                Log.i(TAG, "run: " + imgLocalPath);
                try {
                    File fileOrigin = new File(imgPathFromCache);
                    File fileDest = new File(imgLocalPath);
//                    File fileDest = new File(imgLocalPath);
                    Log.i(TAG, "run: "+fileOrigin.length()+"--"+fileOrigin.exists());
                    Log.i(TAG, "run: "+fileDest.length()+"--"+fileDest.exists());
                    copyFileUsingFileStreams(fileOrigin,fileDest );
                    mhandler.sendEmptyMessage(0);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public String getImgPathFromCache(String url) {
        FutureTarget<File> fileFutureTarget = Glide.with(this)
                .load(url)
                .downloadOnly(100, 100);
        try {
            File cachefile = fileFutureTarget.get();
            String absolutePath = cachefile.getAbsolutePath();
            return absolutePath;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
